import re
from io import BytesIO

from django.conf import settings
from django.contrib.auth import login, logout, authenticate
from django.core.mail import send_mail
from django.http import HttpResponse
from django.views.decorators.http import require_POST
from django.shortcuts import redirect, reverse
from django.core.cache import cache

from apps.ynauth.models import User
from utils import restful
from utils.captcha.lincaptcha import Captcha
from .forms import LoginForm, SignupForm


@require_POST
def login_view(request):
    """
    post登录请求
    :param request:请求上下文
    :return: http响应
    """
    form = LoginForm(request.POST)
    if not form.is_valid():
        errors = form.get_error()
        return restful.params_error(message=errors)

    email = form.cleaned_data.get('email')
    password = form.cleaned_data.get('password')
    remember = form.cleaned_data.get('remember')
    user = authenticate(request, username=email, password=password)

    if not user:
        return restful.params_error(message='账号或密码错误')

    if not user.is_active:
        return restful.unauth(message='您的账号已经被冻结')

    login(request, user)

    if remember:
        request.session.set_expiry(None)
    else:
        request.session.set_expiry(0)

    return restful.ok()


def logout_view(request):
    """
    退出登录
    :param request: 请求上下文
    :return: 重定向到首页
    """
    logout(request)
    return redirect(reverse('index'))


@require_POST
def register_view(request):
    """
    用户注册
    :param request:
    :return:
    """
    form = SignupForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data.get('email')
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        user = User.objects.create_user(email=email, username=username, password=password)
        login(request, user)
        return restful.ok()
    else:
        return restful.params_error(message=form.get_error())


def img_captcha(request):
    """
    请求图形验证码
    :param request: 请求上下文
    :return: 一个img的http响应
    """
    text, image = Captcha.gene_code()
    cache.set(text.lower(), text.lower(), 4 * 60)
    out = BytesIO()
    image.save(out, 'png')
    out.seek(0)
    response = HttpResponse(content_type='image/png')
    response.write(out.read())
    response['Content-length'] = out.tell()
    return response


@require_POST
def email_captcha(request):
    email = request.POST.get('email', 'error')
    if re.match(r'[a-zA-Z0-9]+@[a-zA-Z0-9]+\.com', email):
        try:
            captcha = Captcha.gene_text()
            print('邮箱验证码是%s' % captcha)
            send_email(captcha, email)
            # 邮箱验证码过期时间是4分钟
            cache.set(email, captcha, 4 * 60)
            return restful.ok()
        except Exception as e:
            return restful.server_error(message='发送邮件失败！')
    else:
        return restful.params_error(message='请输入正确格式的邮箱！')


def send_email(captcha, recipient):
    message = '您正在进行注册操作，本次的验证码是 ' + str(captcha) + '，请注意查收!'
    send_mail(subject='yunni', message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[recipient])
